<template src="./template.html">

</template>

<script>
    import {imService} from '@/services'
    import util from '@/utils/util.js'
    import Loading from '@/components/loading.vue'
    // var util = require ('../../utils/util.js')
    var tls = require('../../utils/im/tls.js')
    var webim = require('../../utils/im/webim.js')

    var webimhandler = require('../../utils/im/webim_handler.js')

    export default {

        data() {
            var serverUrl="http://skyforest.static.elab-plus.com/";
            return {
                serverUrl:serverUrl,
                backButton:`${serverUrl}im/back-button.png`,
                adviserName:'顾问',
                localCustomerId:null,
                adviserId:null,
                Identifier: null,
                title:'在线咨询',
                adviserInfo:null,
                UserSig: null,
                msgKey:'',
                dialog:false,
                fixTop:false,
                showVideo:null,
                fixBottom:true,
                houseid:'109',
                loading:false,
                messageNone:false,
                isBusy:false,
                putMess:false,
                imgUrl:'',
                LastMsgTime:0,
                currentMessage: '',
                userInfo: {nickName:localStorage.getItem('tmpMobile')||'web用户'},
                Config:{
                    sdkappid: 1400091043
                    ,
                    accountType: 26432,
                    accountMode: 0 //帐号模式，0-表示独立模式，1-表示托管模式
                },
                localMessages:[
                ]
            }
        },
        components: {
            Loading
        },
        computed:{
            busyButton(){
                return this.isBusy?`${this.serverUrl}im/offline.png`:`${this.serverUrl}im/online.png`
            }
        },
        created(){
            if(this.$route.query&&this.$route.query.houseid==102){
                this.Config.sdkappid = 1400075851;
                this.Config.accountType = 24512;
                this.houseid = this.$route.query.houseid;
                sessionStorage.setItem('imhouseid',this.$route.query.houseid)
            }
        },
        mounted() {
            util.setTitle(this.title);

            if(!(localStorage.getItem('localCustomerId'+this.houseid)&&sessionStorage.getItem('adviserInfo'))){
                this.$router.push({path:'./adviserList',query:this.$route.query.pathName})
            }
            window.addEventListener('resize', () => {
                if (document.activeElement.tagName == 'INPUT') {
                    window.setTimeout(() => {
                        document.activeElement.scrollIntoViewIfNeeded();
                    },100)
                } })

            this.init();
            // 注册虚拟账号，登陆腾讯云
            // this.overscroll(document.querySelector('#message-fixBox'))
            // document.querySelector('body').addEventListener('touchmove',function(e){
            //    if(!e._isScroller){
            //        e.preventDefault();
            //    }
            // },false);

            document.getElementById('message-fixBox').addEventListener('touchmove', this.bodyMove,false);
            window.addEventListener('scroll', this.tabScroll, false);
            // document.getElementById("input-box").scrollIntoView(false);
            $('#input-box').focus(function(){
                setTimeout(function() {
                        window.scrollTo(0,10000)
                    },500
                    // window.scrollTop($('.message-container').height() - window.innerHeight +100);}, 500
                );
            })
            console.log('=========',document.getElementsByClassName('message-container'))
        },
        beforeDestroy() {
            document.querySelector('body').removeEventListener('touchmove',function(e){
                e.preventDefault();
            });
            window.removeEventListener('scroll', this.tabScroll, false)
        },
        methods: {
            overscroll(e){
                e.addEventListener('touchstart',function(){
                    console.log('fff')
                    var top = e.scrollTop,totalScroll = e.scrollHeight,currentScroll = top+e.offsetHeight;
                    if(top===0){
                        e.scrollTop = 1;

                    }else if(currentScroll===totalScroll){
                        e.scrollTop = top-1
                    }
                })
                e.addEventListener('touchmove',function(evt){
                    console.log(e.offsetHeight,e.scrollHeight)

                    console.log('gggggg')
                    evt._isScroller = true

                })
            },
            tabScroll(){

                let scrollT =document.documentElement.offsetTop||document.body.scrollTop
                let distence = $('.message-fixBox').offset().top - scrollT;
                // 上拉加载更早的历史消息
                console.log( $('.message-fixBox').offset().top,scrollT,distence,'距离')
                ;
                if(this.messageNone&&( distence>0||distence==0)){
                    if(this.putMess){
                        this.putMess = false;
                        this.loadMessage()
                    }
                }
            },
            bodyMove(e){
                // e.stopPropagation()
            },
            showDialog(val,url,count){
                if(url){
                    this.imgUrl = url;
                }
                if(count==1){
                    this.showVideo = false
                }else{
                    this.showVideo = true
                }
                console.log(url, this.showVideo,'gggggg')

                this.dialog = val;
            },
            async init(){

                this.loading = true
                this.adviserInfo =JSON.parse(sessionStorage.getItem('adviserInfo'));
                console.log(this.adviserInfo,'ffefe')
                imService.getUserSig(util.reformParam(util.chatUrl,{
                    dynatownId:this.adviserInfo.id,
                    customerId:localStorage.getItem('localCustomerId'+this.houseid).substring(0,localStorage.getItem('localCustomerId'+this.houseid).indexOf('_'))||'',
                    houseid:this.houseid,
                }))
                if(this.adviserInfo){
                    if(this.adviserInfo.userId&&this.adviserInfo.tel&&this.adviserInfo.houseid){
                        this.adviserId = `${this.adviserInfo.userId}_${this.adviserInfo.tel}_${this.adviserInfo.houseid}`
                    }
                    if(this.adviserInfo.id){
                        let result =await imService.getSingleAdviser({id:this.adviserInfo.id,houseid:this.houseid})
                        if(result.data.success){
                            this.isBusy = result.data.single.is_busy
                        }
                    }
                    if(this.adviserInfo.To_Account){
                        let account = this.adviserInfo.To_Account
                        let result =await imService.getSingleAdviser({id:account.substring(0,account.indexOf('_')),houseid:this.houseid})
                        if(result.data.success){
                            this.adviserName = result.data.single.name;
                        }
                        this.adviserId = this.adviserInfo.To_Account
                    }
                }
                if(this.adviserInfo.name){
                    this.adviserName = this.adviserInfo.name
                }

                if(localStorage.getItem('localCustomerId'+this.houseid)){
                    this.localCustomerId = localStorage.getItem('localCustomerId'+this.houseid);
                }
                this.onload();
            },
            loadMessage(){
                this.loading = true;
                setTimeout(()=>{
                    this.loading = false
                },2000)
                var that = this
                // let storageMessage = JSON.parse(localStorage.getItem(this.localCustomerId+'&'+this.adviserId))
                //     this.localMessages = storageMessage||[];
                setTimeout(()=>{
                    webimhandler.getC2CHistoryMsgs(function (data) {
                        if(data.elems[0].type&&data.elems[0].type=='TIMSoundElem'){
                            return
                        }
                        if(data.elems[0].content.text.includes('【系统消息】')){
                            return
                        }
                        if(data.elems[0].content.text.includes('csyzwfelab20180425hhhdfq')){
                            var tempObj = JSON.parse(data.elems[0].content.text);
                            if(tempObj.type==502||tempObj.type==104||tempObj.type==513||tempObj.type==512||tempObj.type==508){
                                return
                            }
                            data.elems[0].content = tempObj;
                            if(data.elems[0].content.type==515||data.elems[0].content.type==516){
                                data.elems[0].local = false;
                                data.elems[0].time =util.formatTodayTime(new Date(data.time*1000));
                                that.localMessages.unshift(data.elems[0]);
                                return
                            }
                        }else{
                            data.elems[0].content = data.elems[0].content.text;
                        }
                        if(data.fromAccount==that.localCustomerId){
                            data.elems[0].local = true
                        }else{
                            data.elems[0].local = false;
                        }
                        data.elems[0].time =util.formatTodayTime(new Date(data.time*1000));
                        // console.log(data.elems[0],'开心2')
                        that.localMessages.unshift(data.elems[0]);

                    },this.msgKey,this.LastMsgTime,function(msgKey,LastMsgTime){
                        that.loading = false;
                        that.msgKey = msgKey;
                        that.LastMsgTime =LastMsgTime;
                        that.putMess = true;
                        that.messageNone = true;

                        // that.loadMessage(msgKey,LastMsgTime)
                    },function(){
                        that.loading = false;
                        that.messageNone = false;
                        console.log(that.messageNone)
                    },function(val){
                        if(val==1){
                            let text='您好，我是您的专属置业顾问，请问有什么可以帮您的吗？'
                            let data = {
                                "csyzwfelab20180425hhhdfq":"secretkey",
                                "param":{
                                    text:text
                                },
                                "type":515,
                                "typedesc":"您好，我是您的专属置业顾问，请问有什么可以帮您的吗？"
                            };
                            setTimeout(async()=>{
                                let result =await imService.getNickname({houseid:that.houseid,dynatownId:that.adviserInfo.id,customerId:that.localCustomerId.substring(0,that.localCustomerId.indexOf('_'))})
                                let nickname = result.data.single.customerName||that.userInfo.nickName||'web用户';
                                webimhandler.onSendMsg(JSON.stringify(data),that.adviserId,nickname,function (msg) {
                                    console.log(msg,'chenggong')
                                    that.receiveMsgs({content:text,type:false},false);
                                });
                            })
                        }

                        setTimeout(()=>{
                            console.log('第一次移到最下方')
                            if($('.message-container').height()>window.innerHeight){
                                console.log($('.message-container').height(),window.innerHeight,$('.message-container').height()-window.innerHeight)
                                //    $('#app').scrollTop($('.message-container').height() - window.innerHeight +100);
                                window.scrollTo(0,$('.message-container').height() - window.innerHeight +100);
                            }
                        },200)
                    },function(err){
                        console.log('没拿回来，继续')
                        // setTimeout(()=>{
                        //     that.loadMessage()
                        // },500)
                        console.log(err)
                    });
                },200)

            },
            async onload(){
                // 拿到userSig
                let result = await imService.getUserSig(util.reformParam(util.accountUrl,{identifier: this.localCustomerId, appId: this.Config.sdkappid}))
                // 用拿到的账号去登陆腾讯云
                this.initIM(this.userInfo,result)

            },
            async initIM(userInfo,res) {
                var that = this;
                var avChatRoomId = '@TGS#1Q3DQEEFH';
                webimhandler.init({
                    accountMode:this.Config.accountMode
                    , accountType: this.Config.accountType
                    , sdkAppID: this.Config.sdkappid
                    , avChatRoomId: avChatRoomId //默认房间群ID，群类型必须是直播聊天室（AVChatRoom），这个为官方测试ID(托管模式)
                    , selType: webim.SESSION_TYPE.C2C
                    , selToID: this.adviserId
                    , selSess: null //当前聊天会话
                });
                //当前用户身份

                var loginInfo = {
                    'sdkAppID': this.Config.sdkappid, //用户所属应用id,必填
                    'appIDAt3rd': this.Config.sdkappid, //用户所属应用id，必填
                    'accountType': this.Config.accountType, //用户所属应用帐号类型，必填
                    'identifier': res.data.single.identifier, //当前用户ID,必须是否字符串类型，选填
                    'identifierNick': this.userInfo.nickName, //当前用户昵称，选填
                    'userSig': res.data.single.signature, //当前用户身份凭证，必须是字符串类型，选填
                };

                //监听（多终端同步）群系统消息方法，方法都定义在demo_group_notice.js文件中
                var onGroupSystemNotifys = {
                    "5": webimhandler.onDestoryGroupNotify, //群被解散(全员接收)
                    "11": webimhandler.onRevokeGroupNotify, //群已被回收(全员接收)
                    "255": webimhandler.onCustomGroupNotify//用户自定义通知(默认全员接收)
                };

                //监听连接状态回调变化事件
                var onConnNotify = function (resp) {
                    switch (resp.ErrorCode) {
                        case webim.CONNECTION_STATUS.ON:
                            //webim.Log.warn('连接状态正常...');
                            break;
                        case webim.CONNECTION_STATUS.OFF:
                            webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
                            break;
                        default:
                            webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
                            break;
                    }
                };


                //监听事件
                var listeners = {
                    "onConnNotify": webimhandler.onConnNotify, //选填
                    "onBigGroupMsgNotify": function (msg) {
                        webimhandler.onBigGroupMsgNotify(msg, function (msgs) {
                            that.receiveMsgs(msgs);
                        })
                    }, //监听新消息(大群)事件，必填
                    "onMsgNotify": function (msg) {
                        webimhandler.onMsgNotify(msg, function (msgs) {
                            var msg = '【系统消息】该用户当前登录方式为web登录，无法使用此功能';
                            if(msgs.content&&msgs.content.type==102||msgs.content.type==508||msgs.content.type==512||msgs.content.type==104){
                                webimhandler.onSendMsg(msg,msgs.fromAccountNick);
                            }else if(msgs.content&&msgs.content.type==502){
                                if(msgs.content.param.isShowInvitation===true||msgs.content.param.isShowInvitation==='true'){
                                    console.log(msgs.content,'ppp')
                                    return
                                }else{
                                    console.log('go')
                                    webimhandler.onSendMsg(msg,msgs.fromAccountNick);
                                }
                            }
                            else if(msgs.content.type==513){
                                return
                            }
                            else if(msgs.content&&(typeof msgs.content=='string')&&msgs.content.includes('onChangePlayAudio')){
                                webimhandler.onSendMsg(msg,msgs.fromAccountNick);
                            }
                            else{
                                if(msgs.fromAccountNick==that.adviserId){
                                    that.receiveMsgs(msgs,false);
                                }

                            }
                            // that.receiveMsgs(msgs,false);
                        })
                    },//监听新消息(私聊(包括普通消息和全员推送消息)，普通群(非直播聊天室)消息)事件，必填
                    "onGroupSystemNotifys": webimhandler.onGroupSystemNotifys, //监听（多终端同步）群系统消息事件，必填
                    "onGroupInfoChangeNotify": webimhandler.onGroupInfoChangeNotify//监听群资料变化事件，选填
                };

                //其他对象，选填
                var options = {
                    'isAccessFormalEnv': true,//是否访问正式环境，默认访问正式，选填
                    'isLogOn': true//是否开启控制台打印日志,默认开启，选填
                };

                if (this.Config.accountMode == 1) {//托管模式
                    webimhandler.sdkLogin(loginInfo, listeners, options, function () {
                        that.addFriend()
                    });
                } else {//独立模式
                    //sdk登录
                    webimhandler.sdkLogin(loginInfo, listeners, options, async function(){
                        // 加载第一次历史消息
                        await that.loadMessage();
                        that.putMess = true;
                    });
                }

            },

            async bindConfirm(e) {

                var that = this;
                var content = this.currentMessage;
                if (!content.replace(/^\s*|\s*$/g, '')) return;
                let result =await imService.getNickname({houseid:that.houseid,dynatownId:that.adviserInfo.id,customerId:that.localCustomerId.substring(0,that.localCustomerId.indexOf('_'))})
                let nickname = result.data.single.customerName||that.userInfo.nickName||'web用户';
                console.log(result.data.single,nickname,'fuidbnfudf')
                webimhandler.setProfilePortrait({'ProfileItem': [{
                        "Tag": "Tag_Profile_IM_Nick",
                        "Value": nickname
                    }]},function(){
                    webimhandler.onSendMsg(content,that.adviserId,nickname, function (msg) {
                        console.log(that.localCustomerId,'张啥样')
                        that.receiveMsgs(msg,true);
                        console.log(that.isBusy,'gre')
                        if(that.isBusy){
                            that.receiveMsgs({content:'您好，非常抱歉，我正在为其他用户服务，稍后回复您！',type:false},false)
                        }
                        that.currentMessage = '';
                    })
                },function(err){
                    console.log(err)
                })


            },
            receiveMsgs: function (data,isLocal) {
                console.log(data,'展示消息')
                data.local= isLocal
                data.time = util.formatTodayTime(new Date());
                this.localMessages.push(data);
                setTimeout(()=>{
                    if($('.message-container').height()>window.innerHeight){
                        console.log($('.message-container').height(),window.innerHeight,$('.message-container').height()-window.innerHeight)

                        window.scrollTo(0,$('.message-container').height() - window.innerHeight +100);
                    }
                },200)
                // 判断是否聊过天,下次打开进入哪种列表看这个是否为true
                if(!localStorage.getItem(this.localCustomerId +'&isSendMsg'+this.houseid)){
                    localStorage.setItem(this.localCustomerId +'&isSendMsg'+this.houseid,true)
                }
                // this.adviserInfo.lastMessage = data;
                // this.adviserInfo.lastMessageTime = new Date().getTime();
                // let messageItem = JSON.parse(localStorage.getItem(this.localCustomerId+'$messageArr'))||[];
                // let flag = false
                // for(var i=0;i<messageItem.length;i++){
                //     if(messageItem[i].created==this.adviserInfo.created){
                //         messageItem[i].lastMessage = this.adviserInfo.lastMessage;
                //         flag = true;
                //     }
                // }
                // if(!flag){
                //     messageItem.push(this.adviserInfo);
                // }
                // localStorage.setItem(this.localCustomerId+'$messageArr',JSON.stringify(messageItem))
            },
            goBack(){
                console.log(this.$store.state.pathName,'dddddd')
                if(localStorage.getItem(this.localCustomerId +'&isSendMsg'+this.houseid)){
                    this.$router.push({path:'./messageList',query:this.$route.query})
                }else{
                    this.$router.push({path:'./adviserList',query:this.$route.query})
                }
            }

        }
    }
</script>

<style lang="scss" scoped>
    @import "./style.scss"
</style>
